import { createClient } from 'redis';
import config from './index';
//连接
const client = createClient({
  url: config.REDIS
});
client.connect();
client.on('error', (err) => console.log('Redis Client Error', err));

//setValue
const setValue = async (key, value, time) => {
   if (typeof value === 'undefined' || value === null || value === '') {
    return
  }
  if (typeof value === 'string') {
    if (typeof time !== 'undefined') {
        client.set(key,value,{'EX': time})
    } else {
         client.set(key,value)
    } 
  } else if (typeof value === 'object') {
    // 遍历对象后，使用hSet
    Object.keys(value).forEach((item) => {
      client.hSet(key, item, value[item], redis.print)
    })
  }
 
}
// getValue
const getValue = async (key) => {
  return await client.get(key)
}

//这里暴露client是为了不用再执行client这个方法。
export { client, setValue, getValue };

